use std::path::Path;

pub fn converter(input: &str, tp: &str) -> String {
    let mut out=String::new();
    let dir = std::env::var("CARGO_MANIFEST_DIR").unwrap();
    let db_path = Path::new(&dir).join("ts.db");
    let conn = rusqlite::Connection::open(db_path).unwrap();
    let mut stmt;
    match tp {
        "s2t"=>{
            stmt = conn.prepare("SELECT s FROM ts WHERE t = ?1").unwrap();
        }
        "t2s"=>{
            stmt = conn.prepare("SELECT t FROM ts WHERE s = ?1").unwrap();
        }
        _=>{panic!("输入错误")}
    }

    let mut wg_iter = stmt.query_map([input], |row| row.get::<usize, String>(0)).unwrap();
    out.push_str(&match wg_iter.next() {
        None => {input.to_string()}
        Some(q) => { q.unwrap() }
    });
    out
}

// mod tests {
//     #[test]
//     fn test() {
//         let dir = std::env::var("CARGO_MANIFEST_DIR").unwrap();
//         let db_path = std::path::Path::new(&dir).join("ts.db");
//         let conn = rusqlite::Connection::open(db_path).unwrap();
//         conn.execute("CREATE TABLE ts (t TEXT PRIMARY KEY, s TEXT)", []).unwrap();
//     }
//     #[test]
//     fn test2() {
//         let j =String::from("学习 老板 头发 发财 皇后 前后 搜刮 魏征 面条 树干 干涉 ");
//         let f =String::from("學習 老闆 頭髮 發財 皇后 前後 搜刮 魏徵 麵條 樹幹 干涉 ");
//         let mut b =std::collections::BTreeMap::new();
//         for c in j.split(' ').zip(f.split(' ')){
//             if c.0!=c.1{
//                 b.insert(c.0,c.1);
//             }
//         }
//         let dir = std::env::var("CARGO_MANIFEST_DIR").unwrap();
//         let db_path = std::path::Path::new(&dir).join("ts.db");
//         let conn = rusqlite::Connection::open(db_path).unwrap();
//         for c in b{
//             conn.execute("INSERT INTO ts (t, s) VALUES (?1, ?2)", [c.0.to_string(),c.1.to_string()]).unwrap();
//         }
//     }
// }
